import { defineStore } from 'pinia'
import { intersection } from 'lodash-es'
import { message } from 'ant-design-vue'
import { post } from '@/utils/request'
import cofirmModal from '@/utils/confirm'
import { getIds } from '@/utils/tools'
import doctorStore from '../../store'

export default defineStore('out-doctor-work-space-circulation', {
  state: () => {
    return {
      tableList: [],
      switchList: {},
      isHaveNewRow: false,
      jzbh: '',
      loading: false
    }
  },
  actions: {
    //创建新行
    generateRow(isChild = false) {
      return {
        id: '',
        yzzt: 0,
        yf: {},
        pl: {},
        key: `row-key-${Math.random().toString().slice(2)}`,
        ...(!isChild && { children: [] }),
        isChild,
        isNew: true
      }
    },
    //创建处方
    generateTable() {
      // const tableKey = 'table-key-' + Math.random().toString().slice(2)
      const cfbh = 'CF' + new Date().getTime()
      const newRow = this.generateRow()
      return {
        tableKey: cfbh,
        cfbh,
        switchChecked: false,
        medicineType: '0',
        expandedRowKeys: [newRow.key],
        dataSource: [{ ...newRow, tableKey: cfbh }]
      }
    },
    //获取处方列表
    async getData(cfbh = '', isCheck = false) {
      this.loading = true
      if (cfbh) {
        this.switchList[cfbh] = isCheck
      }
      const cfList = Object.keys(this.switchList).filter((key) => this.switchList[key])
      const { jzbh } = doctorStore().currentPatient
      this.jzbh = jzbh
      const { data, code } = await post('/outp/mzys/getPatientPrescriptionInfoList', { jzbh, cfList })
      this.loading = false
      if (code !== 0) message.error('获取数据失败')
      this.isHaveNewRow = false
      if (data.length > 0) {
        this.tableList = data.map((item) => {
          const tableKey = item.cfbh
          return {
            tableKey,
            cfbh: item.cfbh,
            medicineType: '0',
            switchChecked: false,
            drugStoreId: item.children[0].drugStoreId || '',
            drugStoreName: item.children[0].drugStoreName || '',
            storeId: item.children[0].drugStoreId || '',
            expandedRowKeys: item.children.map((item) => 'row-key-' + item.id),
            dataSource: item.children.map((child) => ({
              ...child,
              key: 'row-key-' + child.id,
              tableKey,
              children: child.children ? child.children.map((c) => ({ ...c, isChild: true, cfbh: item.cfbh, fkey: child.id, key: c.id })) : []
            }))
          }
        })
      } else {
        this.tableList = [this.generateTable()]
      }
    },
    async addTemplate(tableKey, templateList) {
      const currentTable = this.tableList.filter((item) => item.tableKey === tableKey)[0]
      const currentTableData = currentTable.dataSource
      const currentTableLength = getIds(currentTableData).length
      const templateListLength = getIds(templateList).length
      //判断项目是否大于5
      if (currentTableLength < 5 && currentTableLength + templateListLength > 5) {
        const isConfirm = await cofirmModal({ title: '提示', content: '单张处方不建议超过5个药，是否继续添加？' })
        if (!isConfirm) {
          message.info('已取消添加')
          return false
        }
      }
      //判断处方中是否有重复项目
      if (currentTableData[0]?.sfxm?.bh) {
        const currentTableYPBHS = currentTableData.map((item) => item.sfxm?.bh)
        const templateYPBHS = templateList.map((item) => item.bh)
        const repeatIds = intersection(currentTableYPBHS, templateYPBHS)
        if (repeatIds.length > 0) {
          const itemName = currentTableData.find((item) => item.sfxm?.bh === repeatIds[0]).mc
          message.error(`已有项目【${itemName}】，请勿重复添加`)
          return false
        }
      }
      //添加套餐项目
      this.tableList = this.tableList.map((item) => {
        if (item.tableKey === tableKey) {
          const rowKeys = []
          const newData = templateList.map((item) => {
            const key = `row-${Math.random().toString().slice(2)}`
            rowKeys.push(key)
            return { ...item, key, id: null, isNew: true, cfbh: tableKey }
          })
          item.expandedRowKeys = [...item.expandedRowKeys, ...rowKeys]
          item.dataSource = [...item.dataSource, ...newData].filter((item) => item.sfxm?.mc)
        }
        return item
      })
      return true
    },
    async deleteTable(table) {
      if (table.cfbh) {
        const { jzbh } = doctorStore().currentPatient
        const { code, msg } = await post('/outp/mzys/doDelOutpClinicalPrescriptionHead', {
          cfbh: table.cfbh,
          jzbh
        })
        if (code !== 0) return message.error(msg || '作废失败')
        message.success('作废成功')
        this.getData()
      } else {
        const index = this.tableList.findIndex((item) => item.tableKey === table.tableKey)
        this.tableList.splice(index, 1)
      }
    },
    addTable() {
      const newTable = this.generateTable()
      this.tableList.push(newTable)
    },
    async clickAddTable() {
      doctorStore().tableKey = this.tableList[this.tableList.length - 1].tableKey
    }
  }
})
